<template>
  <div class="expert-qa">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-right">
            <h2>专家问答</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="qa-card">
              <template #header>
                <div class="card-header">
                  <span>在线专家</span>
                </div>
              </template>
              
              <div class="expert-grid" v-loading="loading">
                <el-card 
                  v-for="expert in onlineExperts" 
                  :key="expert.userId" 
                  class="expert-card"
                  @click="startChat(expert)"
                >
                  <div class="expert-info">
                    <el-avatar 
                      :size="80" 
                      :src="expert.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                    />
                    <h3 class="expert-name">{{ expert.callName || expert.userName }}</h3>
                    <div class="expert-status">
                      <el-tag type="success" size="small">在线</el-tag>
                    </div>
                    <p class="expert-bio">{{ expert.bio || '这位专家很神秘，还没有留下介绍' }}</p>
                  </div>
                </el-card>
              </div>
              
              <div class="empty-placeholder" v-if="onlineExperts.length === 0">
                <el-empty description="暂无在线专家" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="8" v-if="userStore.userInfo?.roleId === 3 && userStore.userInfo?.applyType === 1">
            <!-- 最近聊天列表 -->
            <div class="recent-chats">
              <h3>最近的聊天</h3>
              <template v-if="chatMessages.length > 0">
                <el-card class="chat-list">
                  <div 
                    v-for="msg in chatMessages" 
                    :key="msg.fromUserId + msg.createTime"
                    class="chat-item"
                    @click="startChat({userId: msg.fromUserId})"
                  >
                    <span class="user-id">用户 {{ msg.fromUserId }}</span>
                    <p class="message-preview">{{ msg.content }}</p>
                    <span class="message-time">{{ formatTime(msg.createTime) }}</span>
                  </div>
                </el-card>
              </template>
              <template v-else>
                <el-empty description="暂无聊天消息" />
              </template>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const onlineExperts = ref([])
const chatMessages = ref([])
let ws = null

// 如果当前用户是专家，初始化WebSocket连接
const initExpertWebSocket = () => {
  const currentUserId = userStore.userInfo?.userId
  if (!currentUserId) {
    console.log('未获取到用户ID，无法建立WebSocket连接')
    return
  }

  console.log('当前用户ID:', currentUserId)
  console.log('当前用户角色:', userStore.userInfo?.roleId)

  const wsUrl = `ws://localhost:8888/ws/chat/${currentUserId}/0`
  console.log('尝试建立WebSocket连接:', wsUrl)
  
  try {
    ws = new WebSocket(wsUrl)

    ws.onopen = () => {
      console.log('专家WebSocket连接已建立，专家ID:', currentUserId)
      // 连接建立后重新加载专家列表
      setTimeout(loadOnlineExperts, 1000) // 延迟1秒后重新加载列表
    }

    ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      console.log('收到新消息:', message)
      chatMessages.value.push(message)
      // 显示消息通知
      ElMessage({
        message: `收到来自用户 ${message.fromUserId} 的新消息: ${message.content}`,
        type: 'success',
        duration: 5000,
        showClose: true,
        onClick: () => {
          // 点击消息通知跳转到聊天页面
          router.push(`/expert-qa/chat/${message.fromUserId}`)
        }
      })
    }

    ws.onerror = (error) => {
      console.error('专家WebSocket连接错误:', error)
    }

    ws.onclose = (event) => {
      console.log('专家WebSocket连接已关闭', event)
    }
  } catch (error) {
    console.error('建立WebSocket连接失败:', error)
  }
}

// 加载在线专家列表
const loadOnlineExperts = async () => {
  loading.value = true
  try {
    const response = await request({
      url: '/api/chat/experts/online',
      method: 'get'
    })
    
    console.log('获取在线专家列表响应:', response)
    
    // 检查响应中是否包含数据
    if (response && Array.isArray(response)) {
      onlineExperts.value = response
      if (response.length === 0) {
        ElMessage.info('暂无在线专家')
      }
    } else if (response?.code === 200) {
      onlineExperts.value = response.data || []
      if (response.data?.length === 0) {
        ElMessage.info(response.message || '暂无在线专家')
      }
    } else {
      ElMessage.error(response?.message || '获取在线专家列表失败')
      onlineExperts.value = []
    }
  } catch (error) {
    console.error('获取在线专家列表失败:', error)
    ElMessage.error('获取在线专家列表失败')
    onlineExperts.value = []
  } finally {
    loading.value = false
  }
}

// 开始与专家聊天
const startChat = (expert) => {
  router.push(`/expert-qa/chat/${expert.userId}`)
}

// 格式化时间
const formatTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  const currentUser = userStore.userInfo
  console.log('当前用户信息:', currentUser)
  
  // 检查当前用户是否是专家
  const isExpert = currentUser?.roleId === 3 && currentUser?.applyType === 1
  console.log('是否是专家:', isExpert, '角色ID:', currentUser?.roleId, '申请类型:', currentUser?.applyType)
  
  if (isExpert) {
    console.log('当前用户是专家，准备建立WebSocket连接')
    initExpertWebSocket()
  } else {
    console.log('当前用户不是专家，只加载专家列表')
  }
  
  loadOnlineExperts()
})

onUnmounted(() => {
  if (ws) {
    ws.close()
  }
})
</script>

<style scoped>
.expert-qa {
  height: 100vh;
  background-color: #f5f7fa;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.qa-card {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.expert-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 10px;
}

.expert-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.expert-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.expert-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px;
}

.expert-name {
  margin: 15px 0 5px;
  font-size: 18px;
  font-weight: 600;
}

.expert-status {
  margin-bottom: 10px;
}

.expert-bio {
  color: #666;
  font-size: 14px;
  margin: 10px 0 0;
  line-height: 1.4;
}

.empty-placeholder {
  padding: 40px 0;
}

.recent-chats {
  margin-bottom: 20px;
}

.recent-chats h3 {
  margin-bottom: 15px;
  color: #333;
}

.chat-list {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}

.chat-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item:last-child {
  border-bottom: none;
}

.user-id {
  font-weight: bold;
  color: #409EFF;
}

.message-preview {
  margin: 5px 0;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.el-row {
  margin-bottom: 20px;
}
</style> 